package studyguide.ch07;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.TextBox;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

public class TextBoxMidlet extends MIDlet {

	private final TextBox textBox;
	private final Command exitCommand;
	private final Display display;
	
	private class SampleCommandListener implements CommandListener {

		public void commandAction(Command command, Displayable displayable) {
			if (command == exitCommand) {
				String text = textBox.getString();
				System.out.println("Entered text:" + text);
				destroyApp(true);
				notifyDestroyed();
			} else {
				throw new RuntimeException("UNKNOWN COMMAND" + command);
			}
		}
		
	}
	
	public TextBoxMidlet() {
		textBox = new TextBox(
				"TextBox Sample",
				"Text sample. ",
				500,
				TextField.ANY 
				 | TextField.INITIAL_CAPS_SENTENCE
				 | TextField.SENSITIVE);
		exitCommand = new Command("Exit", Command.EXIT, 1);

		textBox.addCommand(exitCommand);
		SampleCommandListener listener = new SampleCommandListener();
		textBox.setCommandListener(listener);
		display = Display.getDisplay(this);
	}
	
	protected void destroyApp(boolean unconditional) {
		// No Op
	}

	protected void pauseApp() {
		// No Op
	}

	protected void startApp() throws MIDletStateChangeException {
		System.out.println("Starting (or restarting) application");
		display.setCurrent(textBox);
	}

}
